<template>
  <div class="blog-container">
    <!-- 主内容区 -->
    <a-layout-content class="content">
      <div class="container">
        <a-row :gutter="24">
          <!-- 左侧作者信息 -->
          <a-col :xs="24" :sm="24" :md="24" :lg="6">
            <a-card class="author-card">
              <div class="author-header">
                <a-avatar size="large" :src="user.avatar" class="author-avatar" />
                <h3 class="author-name">{{ user.nickName }}</h3>
                <p class="author-intro">{{ user.introduction }}</p>
              </div>

              <!-- <div class="author-stats">
                <div class="stat-item">
                  <span class="stat-value">{{ countArticle }}</span>
                  <span class="stat-label">原创</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ countLiked }}</span>
                  <span class="stat-label">获赞</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ countFans }}</span>
                  <span class="stat-label">粉丝</span>
                </div>
              </div> -->

              <!-- <div class="author-actions">
                <a-button type="primary" class="follow-btn" :loading="followLoading" @click="followAuthor(user.id)">
                  {{ isFollow ? '已关注' : '+ 关注' }}
                </a-button>
                <a-button type="text" class="message-btn" @click="sendMsg(user.id)">
                  <a-icon type="message" /> 私信
                </a-button>
              </div> -->
            </a-card>
          </a-col>

          <!-- 中间文章内容 -->
          <a-col :xs="24" :lg="12">
            <a-card class="article-card">
              <!-- 文章标题区 -->
              <div class="article-header">
                <h1 class="article-title">{{ detailObj.title }}</h1>

                <div class="article-meta">
                  <span class="meta-item">
                    <CalendarOutlined />{{ detailObj.createTime }}
                  </span>
                  <span class="meta-item">
                    <ReadOutlined />{{ detailObj.viewCount }} 阅读
                  </span>
                  <span class="meta-item">
                    <CommentOutlined />{{ detailObj.commentCount }} 评论
                  </span>
                  <span class="meta-item">
                    <FileWordOutlined />{{ detailObj.wordCount }} 字数
                  </span>
                </div>

                <div class="article-tags">
                  <a-tag v-for="tag in tags" :key="tag.id" class="article-tag">
                    {{ tag.name }}
                  </a-tag>
                </div>
              </div>

              <!-- 文章内容区 -->
              <div class="article-content">
                <div v-html="detailObj.htmlContent" class="markdown-content"></div>
                <!-- <v-md-preview :text="detailObj.mdContent" ref="previewRef"></v-md-preview> -->
              </div>

              <!-- 文章信息栏 -->
              <div class="article-info-bar" v-if="detailObj.remark">
                {{ detailObj.remark }}
              </div>

              <!-- 互动工具栏 -->
              <div class="interactive-tools">
                <a-button type="text" class="tool-btn" @click="addArticleLike">
                  <span>
                    <HeartFilled v-if="detailObj.isLike" style="color: red;" />
                    <HeartOutlined v-else />
                    &nbsp;点赞
                  </span>
                  <span class="tool-count">{{ detailObj.likeCount }}</span>
                </a-button>
                <a-button type="text" class="tool-btn" :class="{ active: detailObj.collectStatus === 1 }"
                  @click="addArticleCollect">
                  <span>
                    <StarFilled v-if="detailObj.isCollect" style="color: #feb432;" />
                    <StarOutlined v-else />
                    &nbsp;收藏
                  </span>
                  <span class="tool-count">{{ detailObj.collectCount }}</span>
                </a-button>
                <a-button type="text" class="tool-btn" @click="copyCurrentUrl">
                  <span>
                    <ShareAltOutlined />&nbsp;分享
                  </span>
                </a-button>
              </div>

              <!-- 评论区标题 -->
              <template v-if="detailObj.isComment === 1">
                <div class="comment-section-title">
                  <span>
                    <MessageOutlined />&nbsp;评论区
                  </span>
                  <div class="comment-count">
                    <CommentOutlined />&nbsp;{{ detailObj.commentCount }} 条评论
                  </div>
                </div>
                <CommentView @sendComment="clickCommentInfo" :moduleId="moduleId" :showTitle="false"
                  :title="commentTitle"></CommentView>
              </template>
            </a-card>
          </a-col>

          <!-- 右侧边栏 -->
          <a-col :xs="24" :sm="24" :md="24" :lg="6">
            <!-- 文章目录 -->
            <a-card class="sidebar-card toc-card">
              <div class="sidebar-title">文章目录</div>
              <div class="article-toc">
                <ArticleTree :html="detailObj.htmlContent"></ArticleTree>
              </div>
            </a-card>

          </a-col>
        </a-row>
      </div>
    </a-layout-content>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import CommentView from './CommentView.vue';
import { findArticleById, likeArticle, collectArticle } from '@/api/article.js';
import {
  CalendarOutlined,
  CommentOutlined,
  FileWordOutlined,
  HeartFilled,
  HeartOutlined,
  MessageOutlined,
  ReadOutlined,
  ShareAltOutlined,
  StarFilled,
  StarOutlined,
} from '@ant-design/icons-vue';
import ArticleTree from "@/components/ArticleTree.vue";
import { message } from 'ant-design-vue';
import { useUserStore } from '@/stores/user'

const userStore = useUserStore();
const route = useRoute();
// 文章ID
const articleId = route.query.id;
// 模块ID
const moduleId = "4@" + articleId;
// 评论区标题
const commentTitle = ref("");
// 文章详情
const detailObj = reactive({
  id: '',
  title: '',
  createTime: '',
  viewCount: 0,
  likeCount: 0,
  commentCount: 0,
  collectCount: 0,
  html: '',
  isLike: false,
  isCollect: false,
  isComment: 0,
});
// 作者信息
const user = ref({
  id: '',
  nickName: '',
  userName: '',
  avatar: '',
  introduction: '',
});
// 标签
const tags = ref([]);
// 获取发送的评论信息
const clickCommentInfo = (val) => {
  if (val && val.commentId) {
    detailObj.commentCount++;
  }
}
// 获取文章详情
const getArticleDetail = () => {
  findArticleById(articleId).then((res) => {
    console.log(res)
    if (res.code === 200) {
      let userInfo = res.data.userInfo;
      user.value.introduction = userInfo.remark;
      user.value.avatar = userInfo.avatar;
      user.value.id = userInfo.id;
      user.value.nickName = userInfo.nickName;
      user.value.userName = userInfo.username;
      tags.value = res.data.tagList.map(item => ({ id: item.id, name: item.tagName }));
      Object.assign(detailObj, res.data.articleInfo);
      detailObj.isLike = res.data.isLike;
      detailObj.isCollect = res.data.isCollect;
    }
  })
}

// 方法：点赞/取消点赞
const addArticleLike = () => {
  if (!userStore.getToken) {
    message.error('请先登录！');
    return;
  }
  if (detailObj.isLike) {
    detailObj.likeCount--;
  } else {
    detailObj.likeCount++;
  }
  detailObj.isLike = !detailObj.isLike;

  likeArticle({ id: articleId }).then((res) => {
    if (res.code === 200 && res.data) {

    }
  });
};

// 方法：收藏/取消收藏
const addArticleCollect = () => {
  if (!userStore.getToken) {
    message.error('请先登录！');
    return;
  }
  if (detailObj.isCollect) {
    detailObj.collectCount--;
  } else {
    detailObj.collectCount++;
  }
  detailObj.isCollect = !detailObj.isCollect;
  collectArticle({ id: articleId }).then((res) => {
    if (res.code === 200 && res.data) { }
  });
};
// 复制链接
const copyCurrentUrl = async () => {
  try {
    // 获取当前URL
    const url = window.location.href;

    // 使用 Clipboard API 复制到剪贴板
    await navigator.clipboard.writeText(url);

    // 复制成功提示
    message.success('链接已复制！');
  } catch (error) {
    console.error('复制失败:', error);
    // 备选方案：使用 document.execCommand
    fallbackCopyUrl(url);
  }
};
// 备选方案：兼容旧浏览器
const fallbackCopyUrl = (text) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    document.execCommand('copy');
    alert('链接已复制！');
  } catch (err) {
    console.error('备选方案复制失败:', err);
  } finally {
    document.body.removeChild(textArea);
  }
};
// 页面加载完成后执行
onMounted(() => {
  getArticleDetail();
  // 为markdown内容中的图片添加样式
  const images = document.querySelectorAll('.markdown-content img');
  images.forEach(img => {
    img.classList.add('article-image');
  });

});

</script>

<style scoped lang="less">
// 基础变量
@primary-color: #1677ff; // Ant Design主色调
@text-primary: rgba(0, 0, 0, 0.85); // 主要文本色
@text-secondary: rgba(0, 0, 0, 0.65); // 次要文本色
@text-tertiary: rgba(0, 0, 0, 0.45); //  tertiary文本色
@bg-primary: #f5f5f5; // 页面背景色
@bg-card: #ffffff; // 卡片背景色
@border-color: #d9d9d9; // 边框色
@shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.08); // 轻微阴影
@shadow-md: 0 4px 12px rgba(0, 0, 0, 0.1); // 中等阴影
@radius-sm: 4px;
@radius-md: 8px;
@radius-lg: 12px;
@transition: all 0.25s ease;

// 容器宽度
.container {
  margin-top: 30px;
  padding: 0 15px;
}

// 全局样式
.blog-container {
  margin: 0 auto;
  max-width: 1200px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

// 主内容区
.content {
  padding: 30px 0;
  flex: 1;
}

// 作者卡片
.author-card {
  border-radius: @radius-lg;
  box-shadow: @shadow-sm;
  overflow: hidden;
  transition: @transition;

  &:hover {
    box-shadow: @shadow-md;
  }

  .author-header {
    text-align: center;
    padding: 20px 0;

    .author-avatar {
      margin-bottom: 16px;
    }

    .author-name {
      font-size: 18px;
      font-weight: 600;
      color: @text-primary;
      margin-bottom: 8px;
    }

    .author-intro {
      font-size: 14px;
      color: @text-secondary;
      margin: 0 auto;
      max-width: 240px;
    }
  }

  .author-stats {
    display: flex;
    justify-content: space-around;
    padding: 16px 0;
    border-top: 1px solid @border-color;
    border-bottom: 1px solid @border-color;

    .stat-item {
      display: flex;
      align-items: center;

      .stat-value {
        font-size: 18px;
        font-weight: 700;
        color: @primary-color;
      }

      .stat-label {
        font-size: 13px;
        color: @text-secondary;
      }
    }
  }

  .author-actions {
    display: flex;
    gap: 10px;
    padding: 20px 16px 0;

    .follow-btn {
      flex: 1;
      height: 40px;
      border-radius: 20px;
      font-weight: 500;

      &[disabled] {
        background-color: #f5f5f5;
        border-color: #d9d9d9;
        color: rgba(0, 0, 0, 0.25);
      }
    }

    .message-btn {
      height: 40px;
      border-radius: 20px;
      font-weight: 500;
    }
  }
}

// 文章卡片
.article-card {
  border-radius: @radius-lg;
  box-shadow: @shadow-sm;
  overflow: hidden;
  transition: @transition;

  &:hover {
    box-shadow: @shadow-md;
  }

  .article-header {
    margin-bottom: 24px;

    .article-title {
      font-size: 28px;
      font-weight: 700;
      color: @text-primary;
      line-height: 1.3;
      margin-bottom: 16px;

      @media (max-width: 768px) {
        font-size: 22px;
      }
    }

    .article-meta {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      color: @text-secondary;
      font-size: 14px;
      margin-bottom: 20px;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }

    .article-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .article-tag {
        background-color: #e6f7ff;
        color: @primary-color;
        font-size: 12px;
        padding: 4px 10px;
        border-radius: 4px;
      }
    }
  }

  .article-content {
    margin-bottom: 30px;

    // 优化Markdown内容样式
    .markdown-content {
      font-size: 16px;
      line-height: 1.8;
      color: @text-primary;

      h2,
      h3 {
        color: @text-primary;
        margin-top: 30px;
        margin-bottom: 16px;
        font-weight: 600;
      }

      h2 {
        font-size: 22px;
        padding-bottom: 8px;
        border-bottom: 1px solid @border-color;
      }

      p {
        margin-bottom: 16px;
      }

      .article-image {
        border-radius: @radius-sm;
        margin: 20px auto;
        display: block;
        max-width: 100%;
        box-shadow: @shadow-sm;
      }

      pre {
        background-color: #f5f5f5;
        color: @text-primary;
        border-radius: @radius-sm;
        padding: 16px;
        margin: 16px 0;
        overflow-x: auto;
        font-size: 14px;
      }
    }
  }

  .article-info-bar {
    background-color: #fafafa;
    border: 1px solid @border-color;
    border-radius: @radius-sm;
    padding: 16px;
    margin-bottom: 30px;

    .info-item {
      margin-bottom: 10px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      .info-label {
        color: @text-secondary;
        font-weight: 500;
      }

      .info-value {
        color: @text-primary;
      }
    }
  }

  .interactive-tools {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 10px;
    padding-top: 10px;
    border-top: 1px solid @border-color;

    .tool-btn {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 8px 16px;
      color: @text-secondary;
      font-size: 14px;
      cursor: pointer;
      transition: @transition;

      &:hover {
        color: @primary-color;
      }

      &.active {
        color: @primary-color;
      }

      .tool-count {
        margin-left: 4px;
        font-weight: 500;
      }
    }
  }

  .comment-section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    color: @text-primary;
    padding: 16px 0;
    border-top: 1px solid @border-color;

    .comment-count {
      margin-left: auto;
      font-size: 14px;
      font-weight: normal;
      color: @text-secondary;
    }
  }
}

// 侧边栏
.sidebar-card {
  border-radius: @radius-lg;
  box-shadow: @shadow-sm;
  margin-bottom: 20px;
  overflow: hidden;
  transition: @transition;

  &:hover {
    box-shadow: @shadow-md;
  }

  .sidebar-title {
    font-size: 16px;
    font-weight: 600;
    color: @text-primary;
    padding-bottom: 8px;
    border-bottom: 1px solid @border-color;
  }
}

// 文章目录
.toc-card {
  .article-toc {
    max-height: calc(100vh - 160px);
    overflow-y: auto;
    margin-top: 10px;
  }
}

// 推荐文章
.recommend-card {
  .recommend-list {
    .ant-list-item {
      padding: 10px 0;
      border-bottom: 1px solid @border-color;

      &:last-child {
        border-bottom: none;
      }

      .ant-list-item-meta-title {
        a {
          color: @text-primary;
          transition: @transition;

          &:hover {
            color: @primary-color;
          }
        }
      }
    }
  }
}

:deep(.upload-img) {
  margin-top: 2px;
}


// 响应式调整
@media (max-width: 991px) {
  .container {
    padding: 0 10px;
  }

  .article-card,
  .author-card,
  .sidebar-card {
    margin-bottom: 15px;
  }

  .article-title {
    font-size: 22px !important;
  }

  .interactive-tools {
    justify-content: center;
  }
}

// 文章目录样式优化
.toc-card {
  // 关键：设置 sticky 定位，使其随滚动固定在顶部
  position: sticky;
  top: 20px; // 距离顶部的距离
  // 限制最大高度为视口高度减去顶部距离，确保不会超出屏幕
  //max-height: calc(100vh - 40px);
  //overflow: hidden; // 隐藏溢出内容
  //
  //.article-toc {
  //  // 目录内容区域高度填满父容器
  //  height: calc(100% - 40px); // 减去标题高度
  //  max-height: calc(100vh - 80px); // 限制最大高度
  //  overflow-y: auto; // 超出高度时显示垂直滚动条
  //}
}

// 确保父容器不影响sticky定位
.sidebar-card {
  // 移除可能影响定位的overflow属性
  overflow: visible;
}
</style>